package com.yun.interceptor;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;


import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * @Author: fxy
 * @Date: 2022/04/14/15:26
 * @Description:
 */
@Intercepts(
        {@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature
                (
                        type = Executor.class,
                        method = "query",
                        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
                ),
        @Signature
                (
                        type = Executor.class,
                        method = "query",
                        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}
                )}
)
public class ParamInterceptor implements Interceptor {
    String name = "aaa";
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        Object parameterObject = args[1];

        //参数是map
        if(parameterObject instanceof Map){
            //paramMap.get获取不到对象抛异常
            try {
                List<Object> list = (List<Object>) ((Map)parameterObject).get("list");
                if(list!=null&&list.size()>0){
                    for(Object o:list){
                        Field ageField1 =o.getClass().getDeclaredField("name");
                        ageField1.setAccessible(true);
                        ageField1.set(o, name);
                    }
                }
            }catch (Exception e){

            }finally {
                ((Map)parameterObject).put("name",name);
            }
            //参数是对象
        }else {
            Field ageField = parameterObject.getClass().getDeclaredField("name");
            ageField.setAccessible(true);
            ageField.set(parameterObject, name);
        }
        return invocation.proceed();
    }
}
